<template>
	<div class="content">
		<cl-crud @load="onLoad">
			<template #slot-filter>
				<div class="filter-list">
					<div class="filter-item">
						<span class="filter-title">订单状态：</span>
						<el-select
							size="mini"
							filterable
							placeholder="请选择订单状态"
							style="width: 140px"
							v-model="selects.status"
							@change="val => refresh({ status: val, page: 1 })"
						>
							<el-option value label="全部"></el-option>
							<el-option label="待发货" :value="1"></el-option>
							<el-option label="待收货" :value="2"></el-option>
							<el-option label="已完成" :value="3"></el-option>
						</el-select>
					</div>
					<!--                    <div class="filter-item">-->
					<!--                        <span class="filter-title">支付方式：</span>-->
					<!--                        <el-select-->
					<!--                                size="mini"-->
					<!--                                filterable-->
					<!--                                placeholder="请选择支付方式"-->
					<!--                                style="width: 140px"-->
					<!--                                v-model="selects.payType"-->
					<!--                                @change="val => refresh({ payType: val, page: 1 })"-->
					<!--                        >-->
					<!--                            <el-option value label="全部"></el-option>-->
					<!--                            <el-option label="微信" :value="1"></el-option>-->
					<!--&lt;!&ndash;                            <el-option label="支付宝" :value="2"></el-option>&ndash;&gt;-->
					<!--                        </el-select>-->
					<!--                    </div>-->
				</div>
			</template>
			<template #slot-time>
				<div class="filter-list" style="margin-left: 56px;flex-direction: column">
					<div class="filter-item" style="margin-bottom: 10px">
						<span class="filter-title">订单时间：</span>
						<el-radio-group
							class="time-group"
							v-model="selects.createTime"
							size="mini"
							@change="onCreateTimeChange"
						>
							<el-radio-button label="今天"></el-radio-button>
							<el-radio-button label="昨天"></el-radio-button>
							<el-radio-button label="最近7天"></el-radio-button>
							<el-radio-button label="最近30天"></el-radio-button>
							<el-radio-button label="本月"></el-radio-button>
							<el-radio-button label="全部"></el-radio-button>
						</el-radio-group>
						<date-picker
							:newDate="['', '']"
							@change="
								val =>
									crud.refresh({
										startCreateTime: val[0],
										endCreateTime: val[1],
										page: 1
									})
							"
							@refresh="
								crud.refresh({ startCreateTime: '', endCreateTime: '', page: 1 })
							"
						></date-picker>
					</div>
					<div class="filter-item">
						<span class="filter-title">付款时间：</span>
						<el-radio-group
							class="time-group"
							v-model="selects.payTime"
							size="mini"
							@change="onPayTimeChange"
						>
							<el-radio-button label="今天"></el-radio-button>
							<el-radio-button label="昨天"></el-radio-button>
							<el-radio-button label="最近7天"></el-radio-button>
							<el-radio-button label="最近30天"></el-radio-button>
							<el-radio-button label="本月"></el-radio-button>
							<el-radio-button label="全部"></el-radio-button>
						</el-radio-group>
						<date-picker
							:newDate="['', '']"
							@change="
								val =>
									crud.refresh({
										startPayTime: val[0],
										endPayTime: val[1],
										page: 1
									})
							"
							@refresh="crud.refresh({ startPayTime: '', endPayTime: '', page: 1 })"
						></date-picker>
					</div>
				</div>
			</template>
			<template #slot-total>
				<div class="total-list">
					<div class="total-item">
						<h3>订单数量(件)</h3>
						<p>{{ subData.orderNum }}</p>
					</div>
					<div class="total-item">
						<h3>售出商品(件)</h3>
						<p>{{ subData.salesGoods }}</p>
					</div>
					<div class="total-item">
						<h3>订单金额(元)</h3>
						<p>{{ subData.salesAmount.toFixed(2) }}</p>
					</div>
					<div class="total-item">
						<h3>运费金额</h3>
						<p>{{ subData.salesPostPrice.toFixed(2) }}</p>
					</div>
					<div class="total-item">
						<h3>成本金额</h3>
						<p>{{ subData.salesCostprice.toFixed(2) }}</p>
					</div>
					<div class="total-item">
						<h3>净利润</h3>
						<p>{{ subData.salesProfit.toFixed(2) }}</p>
					</div>
				</div>
			</template>
			<template #table-column-userInfo="{ scope }">
				<div class="user-info">
					<p>{{ scope.row.username }}</p>
					<p>{{ scope.row.phone }}</p>
				</div>
			</template>
			<template #table-column-goodsInfo="{ scope }">
				<div class="goods-info" v-for="item in scope.row.goodsMsg" :key="item.pic">
					<img :src="item.pic" />
					<div class="goods-content">
						<p>{{ item.title }}</p>
						<p>
							默认 | <span class="red">¥{{ item.amount }}</span> | x{{ item.count }}
						</p>
					</div>
				</div>
			</template>
			<template #table-column-goodsAmount="{ scope }">
				<p class="red">¥{{ scope.row.goodsAmount }}</p>
			</template>
			<template #table-column-payPrice="{ scope }">
				<p class="red">¥{{ scope.row.payPrice }}</p>
			</template>
			<template #slot-operate="{ scope }">
				<div class="operate-list">
					<el-button
						type="text"
						size="small"
						@click="sendOrder(scope.row)"
						v-if="scope.row.status === 1"
						>发货</el-button
					>
					<el-button
						type="text"
						size="small"
						@click="editAddr(scope.row)"
						v-if="scope.row.status === 1"
						>修改地址</el-button
					>
					<el-button type="text" size="small" @click="orderDetail(scope.row)"
						>订单详情</el-button
					>
				</div>
			</template>
		</cl-crud>

		<cl-form ref="cl-form" key="ordinary"></cl-form>
	</div>
</template>

<script>
/* eslint-disable */
import areaJs from './public/areaJson.js';
import orderStatusJs from './public/orderStatus.js';
import DatePicker from '@/components/DatePicker';
import OrderDetail from './components/OrderDetail';
import moment from 'moment';
export default {
	name: 'ordinary',
	components: {
		DatePicker
	},
	data() {
		return {
			selects: {
				status: '',
				payType: '',
				createTime: '今天',
				payTime: '今天'
			},
			options: {
				express: [
					{
						label: '顺丰快递',
						value: 'sf'
					},
					{
						label: '申通快递',
						value: 'sto'
					},
					{
						label: '圆通快递',
						value: 'yto'
					},
					{
						label: '中通快递',
						value: 'zto'
					},
					{
						label: '韵达快递',
						value: 'yd'
					},
					{
						label: '天天快递',
						value: 'ttk'
					},
					{
						label: 'EMS',
						value: 'ems'
					}
				]
			},
			selectRow: [],
			subData: {
				orderNum: 0,
				salesGoods: 0,
				salesAmount: 0
			},
			/* eslint-disable */
			areaOptions: areaJson,
			areaName: '',
			areaIndex: 0,
			orderStatus: orderStatusJs
		};
	},
	created() {
		if (this.$route.query.status) {
			this.selects.status = Number(this.$route.query.status);
		}
	},
	methods: {
		onLoad({ ctx, app }) {
			this.crud = app;
			ctx.service(this.$service.order.ordinary)
				.set('search', {
					key: {
						placeholder: '请输入商品名称、订单号、用户昵称'
					}
				})
				.set('table', {
					columns: [
						{
							type: 'index',
							label: '序号',
							align: 'center',
							width: '60px'
						},
						{
							label: '订单号',
							prop: 'tradeNo',
							align: 'center',
							width: 200
						},
						{
							label: '用户信息',
							prop: 'userInfo',
							align: 'center',
							width: 150
						},
						{
							label: '商品信息',
							prop: 'goodsInfo',
							align: 'left',
							width: 350
						},
						{
							label: '订单状态',
							prop: 'status',
							align: 'center',
							dict: [
								{
									label: '待发货',
									value: 1
								},
								{
									label: '待收货',
									value: 2
								},
								{
									label: '已完成',
									value: 3
								}
							]
						},
						{
							label: '订单金额',
							prop: 'goodsAmount',
							align: 'center'
						},
						// {
						// 	label: '付款方式',
						// 	prop: 'payType',
						// 	align: 'center',
						// 	dict: [
						// 		{
						// 			label: '其他',
						// 			value: 0
						// 		},
						// 		{
						// 			label: '支付宝',
						// 			value: 1
						// 		},
						// 		{
						// 			label: '微信',
						// 			value: 2
						// 		}
						//     ]
						// },
						{
							label: '实付金额',
							prop: 'payPrice',
							align: 'center'
						},
						{
							label: '订单时间',
							prop: 'createTime',
							align: 'center',
							width: 150,
							sortable: 'custom'
						},
						{
							label: '付款时间',
							prop: 'payTime',
							width: 150,
							align: 'center',
							sortable: 'custom'
						}
					],
					props: {
						'default-sort': {
							prop: 'createTime',
							order: 'descending'
						}
					},
					op: {
						layout: ['slot-operate']
					},
					on: {
						'selection-change': selection => {
							this.selectRow = selection;
						}
					}
				})
				.set('upsert', {
					props: {
						title: '请输入回复内容',
						width: '500px',
						labelWidth: '0px'
					},
					items: [
						{
							prop: 'title',
							component: {
								name: 'el-input',
								attrs: {
									type: 'textarea',
									placeholder: '请输入回复内容',
									clearable: true
								}
							},
							rules: [
								{
									required: true,
									message: '回复内容不能为空'
								}
							]
						}
					]
				})
				.set('layout', [
					['refresh-btn', 'slot-btn', 'slot-filter', 'flex1', 'search-key'],
					['slot-time'],
					['slot-total'],
					['data-table'],
					['flex1', 'pagination']
				])
				.on('refresh', async (params, { next, render }) => {
					const { list, subData } = await next(params);
					this.subData = subData;
					// list.map(e => {
					// 	e.labelList = e.label ? e.label.split(',') : [];
					// });
					render(list);
				})
				.done();
			let params = {};
			if (this.$route.query.status) {
				params.status = this.$route.query.status;
			}
			if (this.selects.createTime === '今天') {
				params.startCreateTime = moment().format('YYYY-MM-DD 00:00:00');
				params.endCreateTime = moment().format('YYYY-MM-DD 23:59:59');
			}
			if (this.selects.payTime === '今天') {
				params.startPayTime = moment().format('YYYY-MM-DD 00:00:00');
				params.endPayTime = moment().format('YYYY-MM-DD 23:59:59');
			}
			app.refresh(params);
		},
		refresh(params) {
			this.crud.refresh(params);
		},
		sendOrder(item) {
			let that = this;
			this.$refs['cl-form'].open({
				props: {
					title: '发货',
					width: '500px',
					showClose: false,
					'label-width': '120px'
				},
				items: [
					{
						prop: 'expressCode',
						label: '快递公司：',
						component: {
							name: 'el-select',
							attrs: {
								placeholder: '请选择快递公司',
								clearable: true
							},
							options: that.options.express
						},
						rules: [
							{
								required: true,
								message: '快递公司不能为空'
							}
						]
					},
					{
						prop: 'expressNo',
						label: '快递单号：',
						component: {
							name: 'el-input',
							attrs: {
								placeholder: '请输入快递单号',
								clearable: true
							}
						},
						rules: [
							{
								required: true,
								message: '快递单号不能为空'
							}
						]
					}
				],
				op: {
					visible: true
				},
				on: {
					submit: ({ data, done, close }) => {
						let expressName = '';
						that.options.express.forEach(item => {
							if (item.value === data.expressCode) {
								expressName = item.label;
							}
						});
						this.$service.order.ordinary
							.deliverGoods({
								id: item.id,
								expressNo: data.expressNo,
								expressCode: data.expressCode,
								expressName: expressName
							})
							.then(() => {
								that.crud.refresh();
								close();
							})
							.catch(err => {
								that.$message.error(err);
								done();
							});
					}
				}
			});
		},
		orderDetail(item) {
			this.$refs['cl-form'].open({
				props: {
					title: '订单详情',
					width: '850px',
					showClose: false,
					'label-width': '0px'
				},
				items: [
					{
						prop: 'orderDetail',
						value: item,
						component: OrderDetail
					}
				],
				op: {
					visible: false
				}
			});
		},
		editAddr(item) {
			let that = this;
			this.$refs['cl-form'].open({
				props: {
					title: '修改地址',
					width: '500px',
					showClose: false,
					'label-width': '120px'
				},
				items: [
					{
						prop: 'addrName',
						label: '收货人：',
						value: item.addrName,
						component: {
							name: 'el-input',
							attrs: {
								placeholder: '请输入收货人',
								clearable: true
							}
						},
						rules: [
							{
								required: true,
								message: '收货人不能为空'
							}
						]
					},
					{
						prop: 'addrPhone',
						label: '收货人电话：',
						value: item.addrPhone,
						component: {
							name: 'el-input',
							attrs: {
								placeholder: '请输入收货人电话',
								clearable: true
							}
						},
						rules: [
							{
								required: true,
								message: '收货人电话不能为空'
							}
						]
					},
					{
						prop: 'areaCode',
						label: '收货地址：',
						value: item.areaCode ? item.areaCode.split(',') : [],
						component: {
							name: 'el-cascader',
							attrs: {
								placeholder: '请选择收货地址',
								clearable: true,
								options: that.areaOptions
							}
						},
						rules: [
							{
								required: true,
								message: '收货地址不能为空'
							}
						]
					},
					{
						prop: 'address',
						label: '详细地址：',
						value: item.address,
						component: {
							name: 'el-input',
							attrs: {
								placeholder: '请输入详细地址',
								clearable: true
							}
						},
						rules: [
							{
								required: true,
								message: '详细地址不能为空'
							}
						]
					}
				],
				op: {
					visible: true
				},
				on: {
					submit: ({ data, done, close }) => {
						that.areaName = '';
						that.areaIndex = 0;
						that.areaErgodic(that.areaOptions, data.areaCode);
						this.$service.order.ordinary
							.update({
								id: item.id,
								addrName: data.addrName,
								addrPhone: data.addrPhone,
								areaCode: data.areaCode.join(','),
								areaName: that.areaName,
								address: data.address
							})
							.then(() => {
								that.crud.refresh();
								close();
							})
							.catch(err => {
								that.$message.error(err);
								done();
							});
					}
				}
			});
		},
		areaErgodic(options, areaCode) {
			options.forEach(item => {
				if (item.value === areaCode[this.areaIndex]) {
					this.areaIndex++;
					this.areaName = this.areaName + item.label;
					if (item.children) {
						this.areaErgodic(item.children, areaCode);
					}
				}
			});
		},
		onCreateTimeChange(val) {
			let params = {};
			if (val === '今天') {
				params.startCreateTime = moment().format('YYYY-MM-DD 00:00:00');
				params.endCreateTime = moment().format('YYYY-MM-DD 23:59:59');
			}
			if (val === '昨天') {
				params.startCreateTime = moment(new Date())
					.add(-1, 'days')
					.format('YYYY-MM-DD 00:00:00');
				params.endCreateTime = moment(new Date())
					.add(-1, 'days')
					.format('YYYY-MM-DD 23:59:59');
			}
			if (val === '最近7天') {
				params.startCreateTime = moment(new Date())
					.add(-6, 'days')
					.format('YYYY-MM-DD 00:00:00');
				params.endCreateTime = moment(new Date())
					.format('YYYY-MM-DD 23:59:59');
			}
			if (val === '最近30天') {
				params.startCreateTime = moment(new Date())
					.add(-29, 'days')
					.format('YYYY-MM-DD 00:00:00');
				params.endCreateTime = moment(new Date())
					.format('YYYY-MM-DD 23:59:59');
			}
			if (val === '本月') {
				params.startCreateTime = moment(
					moment()
						.month(moment().month())
						.startOf('month')
						.valueOf()
				).format('YYYY-MM-DD 00:00:00');
				params.endCreateTime = moment().format('YYYY-MM-DD 23:59:59');
			}
			if (val === '全部') {
				params.startCreateTime = null;
				params.endCreateTime = null;
			}
			this.refresh(params);
		},
		onPayTimeChange(val) {
			let params = {};
			if (val === '今天') {
				params.startPayTime = moment().format('YYYY-MM-DD 00:00:00');
				params.endPayTime = moment().format('YYYY-MM-DD 23:59:59');
			}
			if (val === '昨天') {
				params.startPayTime = moment(new Date())
					.add(-1, 'days')
					.format('YYYY-MM-DD 00:00:00');
				params.endPayTime = moment(new Date())
					.add(-1, 'days')
					.format('YYYY-MM-DD 23:59:59');
			}
			if (val === '最近7天') {
				params.startPayTime = moment(new Date())
					.add(-6, 'days')
					.format('YYYY-MM-DD 00:00:00');
				params.endPayTime = moment(new Date())
					.format('YYYY-MM-DD 23:59:59');
			}
			if (val === '最近30天') {
				params.startPayTime = moment(new Date())
					.add(-29, 'days')
					.format('YYYY-MM-DD 00:00:00');
				params.endPayTime = moment(new Date())
					.format('YYYY-MM-DD 23:59:59');
			}
			if (val === '本月') {
				params.startPayTime = moment(
					moment()
						.month(moment().month())
						.startOf('month')
						.valueOf()
				).format('YYYY-MM-DD 00:00:00');
				params.endPayTime = moment().format('YYYY-MM-DD 23:59:59');
			}
			if (val === '全部') {
				params.startPayTime = null;
				params.endPayTime = null;
			}
			this.refresh(params);
		}
	}
};
</script>

<style lang="stylus" scoped>
.content {
    .goods-info {
        margin-bottom: 10px;
        &:last-child {
            margin-bottom: 0;
        }
        flexBox(space-between, flex-start)
        img {
            width: 80px;
            height: 80px;
            margin-right 10px
        }
        .goods-content {
            flex: 1;
            .price {
                span {
                    color: $main-color
                }
            }
        }
    }
    .operate-list {
        flexBox(center, center, column);
    }
    .red {
        color: $main-color;
    }
}
/deep/.time-group {
    .el-radio-button {
        margin-right 10px;
        .el-radio-button__inner {
            border 1px solid #DCDFE6
            border-radius 4px
            box-shadow: 0 0 0
        }
    }
}
</style>
